﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SqlQueryAnalyzer
{
    public partial class StructIndexForm : BaseForm
    {

        public StructIndexForm()
        {
            InitializeComponent();
            Util.SetTilte(this);
        }

        private void StructIndexForm_Load(object sender, EventArgs e)
        {
            Init();
            
        }
        private void Init()
        {
            try
            {
                List<string> list = SqlStructQuery.GetDatabases();
                this.treeView1.Nodes.Clear();
                this.treeView1.Nodes.AddRange(list.Select(item => new TreeNode { Text = item }).ToArray());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetBaseException().Message, "系统异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void treeView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                TreeNode node = this.treeView1.SelectedNode;

                switch (node.Level)
                {
                    case 0:
                        node.Nodes.Clear();
                        if (cbxSchema.Checked)
                        {
                            node.Nodes.AddRange(SqlStructQuery.GetTables(node.Text).Select(t => new TreeNode
                            {
                                Text = string.Format("{0}.{1}({2})", t.SchemaName, t.TableName, t.Rows),
                                Tag = string.Format("{0}.{1}", t.SchemaName, t.TableName)
                            }).ToArray());
                        }
                        else
                        {
                            node.Nodes.AddRange(SqlStructQuery.GetTables(node.Text).Select(t => new TreeNode
                            {
                                Text = string.Format("{0}({1})", t.TableName, t.Rows),
                                Tag = string.Format("{0}.{1}", t.SchemaName, t.TableName)
                            }).ToArray());
                        }
                        node.Expand();
                        break;
                    case 1:
                        this.gridColumns.DataSource = SqlStructQuery.GetColumns(node.Parent.Text, node.Tag.ToString());
                        this.gridIndexs.DataSource = SqlStructQuery.GetIndexs(node.Parent.Text, node.Tag.ToString());
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetBaseException().Message, "系统异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

      
    }
}
